﻿#include "MetisCharacter.h"
#include "HeadMountedDisplayFunctionLibrary.h"
#include "Camera/CameraComponent.h"
#include "Components/CapsuleComponent.h"
#include "Components/InputComponent.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "GameFramework/Controller.h"
#include "GameFramework/SpringArmComponent.h"
#include "GameFramework/PlayerInput.h"
#include "EngineUtils.h"
#include "MetisDrawActor.h"
#include "Containers/UnrealString.h"
#include "MetisGameMode.h"
#include "MetisCoreTypes.h"

AMetisCharacter::AMetisCharacter()
{
	// Set size for collision capsule
	GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f);

	// set our turn rates for input
	BaseTurnRate = 45.f;
	BaseLookUpRate = 45.f;

	// Don't rotate when the controller rotates. Let that just affect the camera.
	bUseControllerRotationPitch = false;
	bUseControllerRotationYaw = false;
	bUseControllerRotationRoll = false;

	// Configure character movement
	GetCharacterMovement()->bOrientRotationToMovement = true; // Character moves in the direction of input...	
	GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f); // ...at this rotation rate
	GetCharacterMovement()->JumpZVelocity = 600.f;
	GetCharacterMovement()->AirControl = 0.2f;

	// Create a camera boom (pulls in towards the player if there is a collision)
	CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom"));
	CameraBoom->SetupAttachment(RootComponent);
	CameraBoom->TargetArmLength = 300.0f; // The camera follows at this distance behind the character	
	CameraBoom->bUsePawnControlRotation = true; // Rotate the arm based on the controller

	// Create a follow camera
	FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera"));
	FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); // Attach the camera to the end of the boom and let the boom adjust to match the controller orientation
	FollowCamera->bUsePawnControlRotation = false; // Camera does not rotate relative to arm

	//FPS视角初始旋转
	FPSCameraInitRotation = FRotator::ZeroRotator;
	//环绕视角参数
	RoundCameraTargetOffset = FVector::ZeroVector;
	RoundCameraInitRotation = FRotator(-45, 0, 0);
	RoundCameraDistCur = 1000.f;
	RoundCameraDistTarget = 1000.f;
	RoundCameraDistDelta = 200.f;
	RoundCameraDistMin = 100.f;
	RoundCameraDistMax = 20000.f;
	//顶视图视角参数 
	TopCameraTargetOffset = FVector::ZeroVector;
	TopCameraDistCur = 1000.f;
	TopCameraDistTarget = 1000.f;
	TopCameraDistDelta = 200.f;
	TopCameraDistMin = 100.f;
	TopCameraDistMax = 20000.f;
}

void AMetisCharacter::BeginPlay()
{
	Super::BeginPlay();

	AdjustViewportContentSize();

	SetCameraMode(ECameraMode::E_Top);
}

void AMetisCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent)
{
	static bool bBindingsAdded = false;
	if (!bBindingsAdded)
	{
		bBindingsAdded = true;
		UPlayerInput::AddEngineDefinedActionMapping(FInputActionKeyMapping("Key_T", EKeys::T));
		UPlayerInput::AddEngineDefinedActionMapping(FInputActionKeyMapping("Key_MouseWheelUp", EKeys::MouseScrollUp));
		UPlayerInput::AddEngineDefinedActionMapping(FInputActionKeyMapping("Key_MouseWheelDown", EKeys::MouseScrollDown));
	}

	// Set up gameplay key bindings
	check(PlayerInputComponent);
	PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump);
	PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping);
	PlayerInputComponent->BindAction("Key_T", IE_Pressed, this, &AMetisCharacter::NextCamera);
	PlayerInputComponent->BindAction("Key_MouseWheelUp", IE_Pressed, this, &AMetisCharacter::OnMouseWheelUp);
	PlayerInputComponent->BindAction("Key_MouseWheelDown", IE_Pressed, this, &AMetisCharacter::OnMouseWheelDown);

	PlayerInputComponent->BindAxis("MoveForward", this, &AMetisCharacter::MoveForward);
	PlayerInputComponent->BindAxis("MoveRight", this, &AMetisCharacter::MoveRight);
	PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput);
	PlayerInputComponent->BindAxis("TurnRate", this, &AMetisCharacter::TurnAtRate);
	PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput);
	PlayerInputComponent->BindAxis("LookUpRate", this, &AMetisCharacter::LookUpAtRate);
	PlayerInputComponent->BindTouch(IE_Pressed, this, &AMetisCharacter::TouchStarted);
	PlayerInputComponent->BindTouch(IE_Released, this, &AMetisCharacter::TouchStopped);
	PlayerInputComponent->BindAction("ResetVR", IE_Pressed, this, &AMetisCharacter::OnResetVR);
}

void AMetisCharacter::CalcCamera(float DeltaTime, struct FMinimalViewInfo& OutResult)
{
	if (CameraMode == E_FPS)
	{
		if (bFindCameraComponentWhenViewTarget)
		{
			// Look for the first active camera component and use that for the view
			TInlineComponentArray<UCameraComponent*> Cameras;
			GetComponents<UCameraComponent>(/*out*/ Cameras);

			for (UCameraComponent* CameraComponent : Cameras)
			{
				if (CameraComponent->bIsActive)
				{
					CameraComponent->GetCameraView(DeltaTime, OutResult);
					return;
				}
			}
		}

		GetActorEyesViewPoint(OutResult.Location, OutResult.Rotation);
	}
	else 
	{
		FVector CameraLoc(0.f, 0.f, 0.f);
		FRotator CameraRot(0.f, 0.f, 0.f);

		if (CameraMode == E_Round)
		{
			CameraRot.Yaw = GetControlRotation().Yaw;
			CameraRot.Pitch = GetControlRotation().Pitch;
			CameraRot.Roll = 0;
			CameraLoc = RoundCameraTargetOffset;
			CameraLoc -= CameraRot.Vector() * RoundCameraDistCur;

			RoundCameraDistCur = FMath::FInterpTo(RoundCameraDistCur, RoundCameraDistTarget, DeltaTime, 20.f);
		}
		else if (CameraMode == E_Top)
		{
			CameraRot.Yaw = 0;
			CameraRot.Pitch = -90;
			CameraRot.Roll = 0;
			CameraLoc = TopCameraTargetOffset;
			CameraLoc.Z = 2000;
			
			TopCameraDistCur = FMath::FInterpTo(TopCameraDistCur, TopCameraDistTarget, DeltaTime, 20.f);
		}

		OutResult.Location = CameraLoc;
		OutResult.Rotation = CameraRot;
	}

	if (CameraMode == E_Top)
	{
		OutResult.ProjectionMode = ECameraProjectionMode::Orthographic;
		OutResult.OrthoNearClipPlane = 0.f;
		OutResult.OrthoFarClipPlane = 5000.f;
		OutResult.OrthoWidth = TopCameraDistCur;
	}
	else
	{
		OutResult.ProjectionMode = ECameraProjectionMode::Perspective;
	}
}

void AMetisCharacter::OnResetVR()
{
	UHeadMountedDisplayFunctionLibrary::ResetOrientationAndPosition();
}

void AMetisCharacter::TouchStarted(ETouchIndex::Type FingerIndex, FVector Location)
{
	Jump();
}

void AMetisCharacter::TouchStopped(ETouchIndex::Type FingerIndex, FVector Location)
{
	StopJumping();
}

void AMetisCharacter::OnMouseWheelUp()
{
	if (CameraMode == ECameraMode::E_Round)
	{
		RoundCameraDistTarget -= RoundCameraDistDelta;
		RoundCameraDistTarget = FMath::Clamp<float>(RoundCameraDistTarget, RoundCameraDistMin, RoundCameraDistMax);
	}
	else if (CameraMode == ECameraMode::E_Top)
	{
		TopCameraDistTarget -= TopCameraDistDelta;
		TopCameraDistTarget = FMath::Clamp<float>(TopCameraDistTarget, TopCameraDistMin, TopCameraDistMax);
	}
}

void AMetisCharacter::OnMouseWheelDown()
{
	if (CameraMode == ECameraMode::E_Round)
	{
		RoundCameraDistTarget += RoundCameraDistDelta;
		RoundCameraDistTarget = FMath::Clamp<float>(RoundCameraDistTarget, RoundCameraDistMin, RoundCameraDistMax);
	}
	else if (CameraMode == ECameraMode::E_Top)
	{
		TopCameraDistTarget += TopCameraDistDelta;
		TopCameraDistTarget = FMath::Clamp<float>(TopCameraDistTarget, TopCameraDistMin, TopCameraDistMax);
	}
}

void AMetisCharacter::NextCamera()
{
	CameraMode = (enum ECameraMode) (CameraMode + 1);
	if (CameraMode > ECameraMode::E_Top)
	{
		CameraMode = (enum ECameraMode) 0;
	}

	SetCameraMode(CameraMode);
}

void AMetisCharacter::SetCameraMode(ECameraMode InNewMode)
{
	CameraMode = InNewMode;

	if (CameraMode == ECameraMode::E_FPS)
	{
		for (TActorIterator<AActor> ActorItr(GetWorld()); ActorItr; ++ActorItr)
		{
			(*ActorItr)->SetActorHiddenInGame(false);
		}

		GetWorld()->GetGameViewport()->GetEngineShowFlags()->EnableAdvancedFeatures();
		EngineShowFlagOverride(ESFIM_Game, VMI_Lit, *GetWorld()->GetGameViewport()->GetEngineShowFlags(), NAME_None, false);
		FEngineShowFlags* SF = GetWorld()->GetGameViewport()->GetEngineShowFlags();
		SF->SetMotionBlur(true);
		SF->SetTemporalAA(true);
		SF->SetAntiAliasing(true);
		SF->SetWireframe(false);
		SF->SetBloom(true);
		SF->SetPostProcessing(true);
		SF->SetContactShadows(true);
		SF->SetDynamicShadows(true);

		GetController()->SetControlRotation(FPSCameraInitRotation);

		FStringOutputDevice Ar;
		IConsoleManager::Get().ProcessUserConsoleInput(TEXT("showflag.lighting 1"), Ar, GWorld);
	}
	else if (CameraMode == ECameraMode::E_Round)
	{
		for (TActorIterator<AActor> ActorItr(GetWorld()); ActorItr; ++ActorItr)
		{
			(*ActorItr)->SetActorHiddenInGame(false);
		}

		GetWorld()->GetGameViewport()->GetEngineShowFlags()->EnableAdvancedFeatures();
		EngineShowFlagOverride(ESFIM_Game, VMI_Lit, *GetWorld()->GetGameViewport()->GetEngineShowFlags(), NAME_None, false);
		FEngineShowFlags* SF = GetWorld()->GetGameViewport()->GetEngineShowFlags();
		SF->SetMotionBlur(true);
		SF->SetTemporalAA(true);
		SF->SetAntiAliasing(true);
		SF->SetWireframe(false);
		SF->SetBloom(true);
		SF->SetPostProcessing(true);
		SF->SetContactShadows(true);
		SF->SetDynamicShadows(true);

		GetController()->SetControlRotation(FPSCameraInitRotation);

		FStringOutputDevice Ar;
		IConsoleManager::Get().ProcessUserConsoleInput(TEXT("showflag.lighting 1"), Ar, GWorld);
	}
	else if (CameraMode == ECameraMode::E_Top)
	{
		for (TActorIterator<AActor> ActorItr(GetWorld()); ActorItr; ++ActorItr)
		{
			class AMetisDrawActor* DA = Cast<AMetisDrawActor>(*ActorItr);
			if(DA)
				continue;
			(*ActorItr)->SetActorHiddenInGame(true);
		}

		GetWorld()->GetGameViewport()->GetEngineShowFlags()->DisableAdvancedFeatures();
		FEngineShowFlags* SF = GetWorld()->GetGameViewport()->GetEngineShowFlags();
		SF->SetMotionBlur(false);
		SF->SetTemporalAA(true);
		SF->SetAntiAliasing(true);
		SF->SetWireframe(false);
		SF->SetBloom(false);
		SF->SetPostProcessing(false);
		SF->SetContactShadows(false);
		SF->SetDynamicShadows(false);
		EngineShowFlagOverride(ESFIM_Game, VMI_Unlit, *SF, NAME_None, false);

		FStringOutputDevice Ar;
		IConsoleManager::Get().ProcessUserConsoleInput(TEXT("showflag.lighting 0"), Ar, GWorld);
	}
}

void AMetisCharacter::AdjustViewportContentSize()
{
	AMetisGameMode* GM = Cast<AMetisGameMode>(GetWorld()->GetAuthGameMode());
	if (GM)
	{
		//获取户型的包围盒
		FBox HomeBoundingBox = GM->DrawActor->SimpleHome->GetBoudingBox();
		TopCameraTargetOffset = HomeBoundingBox.GetCenter();
		FVector Size = HomeBoundingBox.GetSize();
		//如果南北尺寸大于东西尺寸，则视口投影宽度 = 南北尺寸 * 屏幕横纵比 + 微调距离
		if (Size.X > Size.Y)
		{
			FVector2D ViewportSize;
			GEngine->GameViewport->GetViewportSize(ViewportSize);
			TopCameraDistTarget = ViewportSize.X / ViewportSize.Y * Size.X + 200.f;
		}
		//如果南北尺寸小于东西尺寸，则视口投影宽度直接取东西尺寸
		else
		{
			TopCameraDistTarget = Size.Y + 200.f;
		}
		TopCameraDistCur = TopCameraDistTarget;
	}
}

void AMetisCharacter::TurnAtRate(float Rate)
{
	// calculate delta for this frame from the rate information
	AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds());
}

void AMetisCharacter::LookUpAtRate(float Rate)
{
	// calculate delta for this frame from the rate information
	AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds());
}

void AMetisCharacter::MoveForward(float Value)
{
	if ((Controller != NULL) && (Value != 0.0f))
	{
		if (CameraMode == ECameraMode::E_FPS)
		{
			// find out which way is forward
			const FRotator Rotation = Controller->GetControlRotation();
			const FRotator YawRotation(0, Rotation.Yaw, 0);

			// get forward vector
			const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);
			AddMovementInput(Direction, Value);
		}
		else if (CameraMode == ECameraMode::E_Round)
		{
			RoundCameraTargetOffset += FRotator(0,0,0).Vector() * Value * 160.f * GetWorld()->GetDeltaSeconds() * RoundCameraDistTarget / 500.f;
		}
		else if (CameraMode == ECameraMode::E_Top)
		{
			TopCameraTargetOffset += FRotator(0, 0, 0).Vector() * Value * 160.f * GetWorld()->GetDeltaSeconds() * TopCameraDistTarget / 500.f;
		}
	}
}

void AMetisCharacter::MoveRight(float Value)
{
	if ( (Controller != NULL) && (Value != 0.0f) )
	{
		if (CameraMode == ECameraMode::E_FPS)
		{
			// find out which way is right
			const FRotator Rotation = Controller->GetControlRotation();
			const FRotator YawRotation(0, Rotation.Yaw, 0);

			// get right vector 
			const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);
			// add movement in that direction
			AddMovementInput(Direction, Value);
		}
		else if (CameraMode == ECameraMode::E_Round)
		{
			RoundCameraTargetOffset += FRotator(0, 90, 0).Vector() * Value * 160.f * GetWorld()->GetDeltaSeconds() * RoundCameraDistTarget / 500.f;
		}
		else if (CameraMode == ECameraMode::E_Top)
		{
			TopCameraTargetOffset += FRotator(0, GetControlRotation().Yaw + 90, 0).Vector() * Value * 160.f * GetWorld()->GetDeltaSeconds() * TopCameraDistTarget / 500.f;
		}
	}
}
